package com.thunder.reader.ui;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.xmlpull.v1.XmlPullParserException;

import com.thunder.reader.FeedSettings;
import com.thunder.reader.R;
import com.thunder.reader.parser.OpmlPullParser;
import com.thunder.reader.transaction.BackupAgent;
import com.thunder.reader.transaction.OpmlGenerator;
import com.thunder.reader.transaction.RestoreAgent;
import com.thunder.reader.util.Utility;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class ImportFeedsActivity extends Activity {
    private static final String TAG = FeedSettings.GLOBAL_TAG;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.import_feeds_activity);
        final Button autoSearchButton = (Button) findViewById(R.id.import_feeds_auto_search);
        autoSearchButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                new Thread(new Runnable() {
                    public void run() {
                        importWithOpmlParser();
                    }
                }).start();
            }
        });
        final Button manuallySearchButton = (Button) findViewById(R.id.import_feeds_manual_select);
        manuallySearchButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                exportFeedsToSDcard();
            }
        });
        final Button backupButton = (Button) findViewById(R.id.import_feeds_backup);
        backupButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                backup();
            }
        });
        final Button restoreButton = (Button) findViewById(R.id.import_feeds_restore);
        restoreButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                restore();
            }
        });
    }
    
    private void importWithOpmlParser() {
        try {
            new OpmlPullParser(this, getAssets().open("google-reader-subscriptions.xml")).parse();
            new OpmlPullParser(this, getAssets().open("feeds.xml")).parse();
        } catch (XmlPullParserException e) {
            Log.e(TAG, "pull exception", e);
        } catch (IOException e) {
            Log.e(TAG, "io exception", e);
        }
    }
    
    // path is sd card root
    // file name is feeds.xml, i.e. /sdcard/feeds.xml
    // do nothing if sd card is not writable.
    // Override the file /sdcard/feeds.xml even if the file exists.
    private void exportFeedsToSDcard() {
        final String feeds = "feeds.txt";
        if (!Utility.sdcardWritable()) {
            return;
        }
        try {
            final File root = Environment.getExternalStorageDirectory();
            final OutputStream os = new FileOutputStream(new File(root, feeds));
            new OpmlGenerator(getContentResolver(), os).generate();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    final String filename = "thunder_reader_backup.txt";
    
    // backup to /sdcard
    // currently, we backup feeds and groups only
    private void backup() {
        if (!Utility.sdcardWritable()) {
            return;
        }
//        final String filename = new SimpleDateFormat("yyyyMMDD_hhmmss").format(new Date()) + ".txt";
        try {
            final File root = Environment.getExternalStorageDirectory();
            final OutputStream os = new FileOutputStream(new File(root, filename));
            new BackupAgent(getContentResolver(), os).backup();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private void restore() {
        if (!Utility.sdcardAvailable()) {
            return;
        }
        try {
            final File root = Environment.getExternalStorageDirectory();
            final InputStream is = new FileInputStream(new File(root, filename));
            new RestoreAgent(getContentResolver(), is).restore();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}